//
// Created by YueChuan on 2023/5/4.
//

#include "http_server.h"
#include "log.h"

//TODO 用到了config_servlet.h以及status_servlet.h 现将这两个模块完成

namespace yuechuan {
    namespace http {
        static Logger::ptr g_logger = YUECHUAN_LOG_ROOT();

        HttpServer::HttpServer(bool keepalive, IOManager *worker, IOManager *io_worker, IOManager *accept_worker) :
                TcpServer(worker, accept_worker),
                m_isKeepalive(keepalive) {
            m_dispatch.reset(new ServletDispatch);
        }

        void HttpServer::handleClient(Socket::ptr client) {
            HttpSession::ptr session(new HttpSession(client));
            do {
                auto req = session->recvRequest();
                if (!req) {
                    YUECHUAN_LOG_WARN(g_logger) << "recv http request fail, errno = " << errno << " "
                                                << strerror(errno) << " client = " << *client;
                    break;
                }
                HttpResponse::ptr rsp(new HttpResponse(req->getVersion(), req->isClose() || !m_isKeepalive));
                m_dispatch->handle(req, rsp, session);

                session->sendResponse(rsp);
                if (!m_isKeepalive || req->isClose()) {
                    break;
                }
            } while (m_isKeepalive);
            session->close();
        }

        void HttpServer::setName(const std::string &v) {
            TcpServer::setName(v);
            m_dispatch->setDefault(std::make_shared<NotFoundServlet>(v));
        }
    }
}
